﻿namespace CloudNinja.Metering.Authentication
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;

    public class HttpRequestMessageAdapter : IRequestAdapter
    {
        private readonly HttpRequestMessage httpRequest;

        public HttpRequestMessageAdapter(HttpRequestMessage httpRequest)
        {
            this.httpRequest = httpRequest;
        }

        public string Method
        {
            get
            {
                return this.httpRequest.Method.ToString();
            }
        }

        public string ContentType
        {
            get
            {
                return this.httpRequest.Content.Headers.ContentType.MediaType;
            }
        }

        public string RequestLocalPath
        {
            get
            {
                return this.httpRequest.RequestUri.LocalPath;
            }
        }

        public string Query
        {
            get
            {
                return this.httpRequest.RequestUri.Query;
            }
        }

        public string AuthorizationHeaderValue
        {
            get
            {
                return this.httpRequest.Headers.Authorization.Parameter;
            }
        }

        public IEnumerable<string> HeadersKeys
        {
            get
            {
                return this.httpRequest.Headers.AsEnumerable().Select(h => h.Key);
            }
        }

        public string DateHeader
        {
            get
            {
                return this.GetHeaderValue(HeaderNamesForHmac.DateHeader);
            }

            set
            {
                throw new NotSupportedException("We should not be setting an incoming request's header values");
            }
        }

        public string UserHeader
        {
            get
            {
                return this.GetHeaderValue(HeaderNamesForHmac.UsernameHeaderName);
            }

            set
            {
                throw new NotSupportedException("We should not be setting an incoming request's header values");
            }
        }

        public string GetHeaderValue(string headerName)
        {
            var headers = this.httpRequest.Headers;
            if (headers == null)
            {
                return string.Empty;
            }

            IEnumerable<string> values;
            if (!this.httpRequest.Headers.TryGetValues(headerName, out values))
            {
                return string.Empty;
            }

            return string.Join(string.Empty, values);
        }
    }
}